<?php
class CollectService{
	
	public $dbutil;
	public $zipName = "datas.zip";
	
	public $tempDir = "temp";
	
	public $username;
	public $userid;
	public $password;
	public $websitename;
    public $websiteid;
	

	function __construct($dbutil=null,$userid=null,$username=null,$password=null,$websitename=null,$websiteid=null){

	  	$this->dbutil =  $dbutil;
	  	$this->userid =  $userid;
	  	$this->username = $username;
	  	$this->password = $password;
	  	$this->websitename = $websitename;
		$this->websiteid = $websiteid;


	}
	
	function download(){
        require_once MODEL . DS . "MessageDTO.php";
        require_once MODEL . DS . "UserDTO.php";

        $user = new UserDTO();
        //$user->password=md5("superyuyue");
        //$user->username="superyuyue";
        $user->password=$this->password;
        $user->username=$this->username;
        $user->websiteId=$this->websiteid;
        $user->websiteName=$this->websitename;
		$user->userId = $this->userid;
        $userJson = json_encode($user);

        $message = new MessageDTO();
        $message->code=1;
        $message->message=$userJson;

        $data_string = json_encode($message);

//		var_dump($data_string);
        set_time_limit(0);
		global $CONFIG;
		$url=$CONFIG['DATA_SERVER']['SERVER_BASE_URL']."api/game/gamesbysite";
        $fp = fopen (dirname(__FILE__) . DS.$this->zipName, 'w+');//This is the file where we save the    information

//		var_dump(dirname(__FILE__) . DS.$this->zipName);

        $ch = curl_init(str_replace(" ","%20",$url));//Here is the file we are downloading, replace spaces with %20
        curl_setopt($ch, CURLOPT_TIMEOUT, 5040);
        curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
         curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string))
        );
        curl_exec($ch); // get curl response
        curl_close($ch);

        fclose($fp);
    }
    //the parameter get by constuctor
    // 使用php的 curl api获取发送及获取json数据
    public function check_user(){
            require_once MODEL . DS . "MessageDTO.php";
            require_once MODEL . DS . "UserDTO.php";
            $user = new UserDTO();
            $user->password=md5($this->password);
            $user->username=$this->username;
            $user->websiteName=$this->websitename;

            $userJson = json_encode($user);

            $message = new MessageDTO();
            $message->code=1;
            $message->message=$userJson;
	     	global  $CONFIG;
            $data_string = json_encode($message);
            //这里应该写进配置
		$server_url=$CONFIG['DATA_SERVER']['SERVER_BASE_URL']."api/user/validateuser";
		$ch = curl_init($server_url);
//            $ch = curl_init('http://198.23.115.180:8080/gamesitebuilder/api/user/validateuser');
//            $ch = curl_init('http://localhost:8080/gamesitebuilder/api/user/validateuser');
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data_string))
            );

            $result = curl_exec($ch);
             if($result == "true"){
                 return true;
             }else{
                 return false;
             }
    }
	// 使用php的 curl api获取发送及获取json数据
	public function getUserInfo(){
		require_once MODEL . DS . "MessageDTO.php";
		require_once MODEL . DS . "UserDTO.php";
		$user = new UserDTO();
		$user->password=md5($this->password);
		$user->username=$this->username;
		$user->websiteName=$this->websitename;

		$userJson = json_encode($user);

		$message = new MessageDTO();
		$message->code=1;
		$message->message=$userJson;

		$data_string = json_encode($message);
		//这里应该写进配置
		global $CONFIG;
		$server_url=$CONFIG['DATA_SERVER']['SERVER_BASE_URL']."api/user/getuserinfo";
		$ch = curl_init($server_url);
//		$ch = curl_init('http://198.23.115.180:8080/gamesitebuilder/api/user/getuserinfo');
//		$ch = curl_init('http://localhost:8080/gamesitebuilder/api/user/getuserinfo');
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Content-Type: application/json',
				'Content-Length: ' . strlen($data_string))
		);

		$result = curl_exec($ch);


		return $result;
	}
    public function storage(){
		
		$zipFile = dirname(__FILE__)."/".$this->zipName;
		$outDir = dirname(__FILE__)."/".$this->tempDir."/";
		
		$zip = new ZipArchive();

		if ($zip->open($zipFile) === TRUE) {
		    $zip->extractTo($outDir);
		    $zip->close();
			//delete zip
		    if (file_exists($zipFile)) { 
		    	@unlink ($zipFile);
			}
		    $files = array();
			$dir = dir($outDir);
			while($entry=$dir->read()){    
				if($entry == '.' || $entry == '..') {
					continue;    
				}
				$files[] = $outDir.$entry;
			}
			
			foreach ($files as $fileName){
				$table = "";
				
				if(strpos(":".$fileName,"games.csv") ){
					$table = "game";
				}else if(strpos(":".$fileName,"relation.csv") ){
					$table = "relations";
				}else if(strpos(":".$fileName,"tags.csv") ){
					$table = "tags";
				}
				
				if($table == ""){
				 	continue;
				}
				$sql = null;
				$colum = array();
				
				$file = fopen($fileName,'r'); 
				
				while ($data = fgetcsv($file)) { 
					
					if($sql == null){
						$cols = "";
						$format = "";
						foreach ($data as $col){
							$colName = $this->columGen($col);
							
							if($colName == null || $colName ==''){
								continue;
							}
							
							$colum[] = ':'.$colName;
							$cols = $cols.",".$colName;
							
							if( strpos(':'.$colName,'time') || strpos(':'.$colName,'date') ){
								$format = $format.",str_to_date(:".$colName.",'%a %b %d %H:%i:%s CST %Y')";
							}else{
								$format = $format.",:".$colName;
							}
						}
						$cols = substr($cols, 1);
						$format = substr($format, 1);
						$sql = " insert into ".$table." (".$cols.") value ( ".$format." ) ";
						continue;
					}
					$row = array();
					for($index = 0 ; $index < count($data) ; $index++){
						$colName = $colum[$index];
						$row[$colum[$index]] = $data[$index];
					}
					$this->dbutil->prepareUpdate($sql,$row);
				}
				fclose($file);
				
				//delete 
				if (file_exists($fileName)) { 
			    	@unlink ($fileName);
				}
			}
		} 
    }
    	
	public function columGen($colnum){
		preg_match_all('/([A-Z])/', $colnum ,$rr);  
		if ( count($rr) > 0){
			$r = $rr[0];
			foreach ( $r as $a){
				$colnum = str_replace($a,'_'.$a,$colnum);
			}
		}
		return strtolower($colnum);
	}
	
} 